package com.irdstudio.efp.esb.api.service.sed.ploaninfo;

import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RepayPlanInfo;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalRepayPlan;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalRepayPlan;
import com.irdstudio.efp.esb.api.util.TransferQueryParams;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.service.bo.resp.hj.AcctDtlInfBean;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.LoanRepayPlanVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;

/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】
 * 问题编号：【】
 *
 * @author xiaojunhui
 * @version 0.1
 * @date 2019/5/13 10:12
 */
@Service
public class PersonalRepayPlanService {
    private static Logger logger = LoggerFactory.getLogger(PersonalRepayPlanService.class);

    /**
     * 预言借据号为空
     */
    private final Predicate<ReqPersonalRepayPlan> billNoPredicate = (reqPersonalRepayPlan) -> StringUtils.isEmpty(reqPersonalRepayPlan.getBillNo());

    /**
     * 根据规则封装查询参数
     */
    public final TransferQueryParams<ReqPersonalRepayPlan, LoanRepayPlanVO> transferQueryParams = (reqPersonalRepayPlan) -> {
        LoanRepayPlanVO repayPlanVO = new LoanRepayPlanVO();
        if (!billNoPredicate.test(reqPersonalRepayPlan)) {
            repayPlanVO.setRefNbr(reqPersonalRepayPlan.getBillNo());
        } else {
            throw new BizException("借据号不能为空");
        }
        return repayPlanVO;
    };

    private RepayPlanInfo c2ReplanInfo(AcctDtlInfBean personalLoanRepayPlanVO, String openDay) {
        RepayPlanInfo repayPlanInfo = new RepayPlanInfo();
        repayPlanInfo.setTerm(personalLoanRepayPlanVO.getRpyTime());

        LocalDate sd = LocalDate.parse(personalLoanRepayPlanVO.getStartDt(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate ed = LocalDate.parse(personalLoanRepayPlanVO.getEndDt(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate dd = LocalDate.parse(personalLoanRepayPlanVO.getEndDt(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        ed = Objects.nonNull(personalLoanRepayPlanVO.getGrcPrd())?LocalDate.parse(personalLoanRepayPlanVO.getGrcPrd(), DateTimeFormatter.ofPattern("yyyyMMdd")):ed;
        repayPlanInfo.setStrDt(sd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        repayPlanInfo.setEndDt(dd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        LocalDate od = LocalDate.parse(openDay, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String status = "N";
        //到期日小于当前系统日期，若未还=0，为结清(PO);若未还>0，为逾期(YUQ)
        //到期日大于等当前系统日期，若未还=0 为结清；未还>0，为正常
        //获取未还金额
        BigDecimal notPaid = PloaninfoUtils.getPlanNeedAmt(personalLoanRepayPlanVO);

        if (ed.toEpochDay() < od.toEpochDay()) {
            if (notPaid.intValue() <= 0) {
                status = "P";
            }
            if (notPaid.intValue() > 0) {
                status = "O";
            }
        }else{
            if (notPaid.intValue() <= 0) {
                status = "P";
            }
        }
        //C 撤销
        //F 非应计
        //N 正常
        //O 逾期
        //P 结清
        //R 冲正
        repayPlanInfo.setState(status);
        //期供金额 计划本金+计划利息
        repayPlanInfo.setTermSupplyAmt(PloaninfoUtils.getPlanAmt(personalLoanRepayPlanVO));
        //应还本金=计划本金
        repayPlanInfo.setsPrinAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getPlanPrin()));
        //应还利息=计划利息
        repayPlanInfo.setsIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getPlanInt()));
        //应还罚息=出单罚息+自提罚息
        repayPlanInfo.setsPenIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getIssuePnyInt()).add(personalLoanRepayPlanVO.getAlrdyPrvnPnyInt()));
        //应还复利=出单复利+自提复利
        repayPlanInfo.setsCompIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getIssueCmpdInt()).add(personalLoanRepayPlanVO.getAlrdyPrvnCmpdInt()));
        //应还费用 应还之和
        repayPlanInfo.setsFeeAmt(PloaninfoUtils.getPlanTotalAmt(personalLoanRepayPlanVO));
        //已还本金
        repayPlanInfo.setaPrinAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyPrin()));
        //已还利息
        repayPlanInfo.setaIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyInt()));
        //已还罚息
        repayPlanInfo.setaPenIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyPnyInt()).add(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyOvduePnyInt())));
        //已还复利
        repayPlanInfo.setaCompIntAmt(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyCmpdInt()).add(BigDecimal.valueOf(personalLoanRepayPlanVO.getActRpyOvdueCmpdInt())));
        //已还费用 已还之和
        repayPlanInfo.setaFeeAmt(PloaninfoUtils.getPaided(personalLoanRepayPlanVO));
        //结清日期
        //repayPlanInfo.setSetlDt(personalLoanRepayPlanVO.getClearDate());
        //是否逾期过 0否  1是
        //repayPlanInfo.setIsOverDue(personalLoanRepayPlanVO.getIsOverDue());

        return repayPlanInfo;
    }

    ;


    /**
     * 处理响应结果
     *
     * @param respPersonalRepayPlan
     * @param loanRepayPlanVOS
     * @param offsetLimit
     * @param totalSize
     */
    public void handleResp(RespPersonalRepayPlan respPersonalRepayPlan, AccLoanVO accLoanVO, List<AcctDtlInfBean> loanRepayPlanVOS, int[] offsetLimit, int totalSize, String openDay) {
        respPersonalRepayPlan.setTotalTerm(accLoanVO.getLoanTerm() + "");
        respPersonalRepayPlan.setPrdId(accLoanVO.getPrdId());
        respPersonalRepayPlan.setBillNo(accLoanVO.getBillNo());

        ArrayList<RepayPlanInfo> repayPlanInfos = new ArrayList<RepayPlanInfo>();
        if (loanRepayPlanVOS != null && loanRepayPlanVOS.size() > 0) {
            for (int i = 0; i < loanRepayPlanVOS.size(); i++) {
                AcctDtlInfBean loanRepayPlanVO = loanRepayPlanVOS.get(i);
                repayPlanInfos.add(i, c2ReplanInfo(loanRepayPlanVO, openDay));
            }
        }
        //根据期次做排序，小的在前面
        repayPlanInfos.sort(Comparator.comparingInt(o -> (Integer.parseInt(o.getTerm()))));
        respPersonalRepayPlan.setRetCode(RespRetCode.SUCCESS.getCode());
        respPersonalRepayPlan.setRetMsg("查询成功");
        respPersonalRepayPlan.setRepayPlanArr(repayPlanInfos);
        respPersonalRepayPlan.setPageNo(offsetLimit[2] + "");
        respPersonalRepayPlan.setPagSize(offsetLimit[1] + "");
        respPersonalRepayPlan.setTotalSize(totalSize + "");
    }
}
